package com.virus.mall.controller.mall;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.virus.mall.model.Result;
import com.virus.mall.model.bo.*;
import com.virus.mall.model.vo.GetOrderByStateVo;
import com.virus.mall.service.OrdersService;
import com.virus.mall.service.impl.OrdersServiceImpl;
import com.virus.mall.utils.HttpUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @Classname MallOrderServlet
 * @Description NULL
 * @Date 2021/4/20 14:30
 * @Created by virus
 */
@WebServlet("/api/mall/order/*")
public class MallOrderServlet extends HttpServlet {

    private OrdersService ordersService = new OrdersServiceImpl();

    private ObjectMapper objectMapper = new ObjectMapper();

    {
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        String op = requestURI.replaceAll("/api/mall/order/", "");
        if (op.equals("addOrder")) {
            addOrder(request, response);
        } else if (op.equals("settleAccounts")) {
            settleAccounts(request, response);
        } else if (op.equals("sendComment")) {
            sendComment(request, response);
        }
    }

    /**
     * 加入购物车
     *
     * @param request
     * @param response
     * @throws IOException
     */
    private void addOrder(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        AddOrderBo addOrderBo = null;
        try {
            if (requestBody.substring(requestBody.indexOf("num") + 4
                    , requestBody.indexOf(",", requestBody.indexOf("num") + 4)).contains(".")) {
                response.getWriter().println(objectMapper.writeValueAsString(Result.error("请下单整数数量商品")));
                return;
            }
            addOrderBo = objectMapper.readValue(requestBody, AddOrderBo.class);
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().println(objectMapper.writeValueAsString(Result.error("参数传入错误")));
            return;
        }
        if (addOrderBo.getNum() <= 0) {
            response.getWriter().println(objectMapper.writeValueAsString(Result.error("商品数量不正确")));
            return;
        }
        boolean result = ordersService.addOrder(addOrderBo);
        if (result) {
            response.getWriter().println(objectMapper.writeValueAsString(Result.ok()));
        } else {
            response.getWriter().println(objectMapper.writeValueAsString(Result.error("添加订单失败,可能存在购买商品数量超出库存")));
        }
    }

    /**
     * 下单
     *
     * @param request
     * @param response
     * @throws IOException
     */
    private void settleAccounts(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        SettleAccountsBo settleAccountsBo = null;
        try {
            VerifyDoubleBo verifyDoubleBo = objectMapper.readValue(requestBody, VerifyDoubleBo.class);
            for (VerifyCartDoubleBo verifyCartDoubleBo : verifyDoubleBo.getCartList()) {
                if (verifyCartDoubleBo.getGoodsNum().contains(".")) {
                    response.getWriter().println(objectMapper.writeValueAsString(Result.error("请下单整数数量商品")));
                    return;
                }
            }
            settleAccountsBo = objectMapper.readValue(requestBody, SettleAccountsBo.class);
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().println(objectMapper.writeValueAsString(Result.error("参数传入错误")));
            return;
        }
        for (CartBo cartBo : settleAccountsBo.getCartList()) {
            if (cartBo.getGoodsNum() <= 0) {
                response.getWriter().println(objectMapper.writeValueAsString(Result.error("下单数量不正确")));
                return;
            }
            String goodsNum = String.valueOf(cartBo.getGoodsNum());
            if (goodsNum.contains(".")) {
                response.getWriter().println(objectMapper.writeValueAsString(Result.error("请下单整数数量商品")));
                return;
            }
        }
        boolean result = ordersService.settleAccounts(settleAccountsBo);
        if (result) {
            response.getWriter().println(objectMapper.writeValueAsString(Result.ok()));
        } else {
            response.getWriter().println(objectMapper.writeValueAsString(Result.error("下订单失败，可能存在购买数量大于库存")));
        }
    }

    /**
     * 发送评论
     *
     * @param request
     * @param response
     * @throws IOException
     */
    private void sendComment(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String requestBody = HttpUtils.getRequestBody(request);
        SendCommentBo sendCommentBo = null;
        try {
            sendCommentBo = objectMapper.readValue(requestBody, SendCommentBo.class);
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().println(objectMapper.writeValueAsString(Result.error("参数传入错误")));
            return;
        }
        boolean result = ordersService.sendComment(sendCommentBo);
        if (result) {
            response.getWriter().println(objectMapper.writeValueAsString(Result.ok()));
        } else {
            response.getWriter().println(objectMapper.writeValueAsString(Result.error("发送评论发生错误")));
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        String op = requestURI.replaceAll("/api/mall/order/", "");
        if (op.startsWith("getOrderByState")) {
            getOrderByState(request, response);
        } else if (op.startsWith("deleteOrder")) {
            deleteOrder(request, response);
        } else if (op.startsWith("pay")) {
            pay(request, response);
        } else if (op.startsWith("confirmReceive")) {
            confirmReceive(request, response);
        }
    }

    /**
     * 根据状态获取订单信息
     *
     * @param request
     * @param response
     * @throws IOException
     */
    private void getOrderByState(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String stateStr = request.getParameter("state");
        String token = request.getParameter("token");
        int state;
        try {
            state = Integer.parseInt(stateStr);
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().println(objectMapper.writeValueAsString(Result.error("参数传入错误")));
            return;
        }
        List<GetOrderByStateVo> getOrderByStateVos = ordersService.getOrderByState(state, token);
        response.getWriter().println(objectMapper.writeValueAsString(Result.ok(getOrderByStateVos)));
    }

    /**
     * 删除订单
     *
     * @param request
     * @param response
     * @throws IOException
     */
    private void deleteOrder(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String idStr = request.getParameter("id");
        int id;
        try {
            id = Integer.parseInt(idStr);
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().println(objectMapper.writeValueAsString(Result.error("参数传入错误")));
            return;
        }
        boolean result = ordersService.deleteOrder(id);
        if (result) {
            response.getWriter().println(objectMapper.writeValueAsString(Result.ok()));
        } else {
            response.getWriter().println(objectMapper.writeValueAsString(Result.error("删除订单失败")));
        }
    }

    /**
     * 付款
     *
     * @param request
     * @param response
     * @throws IOException
     */
    private void pay(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String idStr = request.getParameter("id");
        int id;
        try {
            id = Integer.parseInt(idStr);
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().println(objectMapper.writeValueAsString(Result.error("参数传入错误")));
            return;
        }
        boolean result = ordersService.pay(id);
        if (result) {
            response.getWriter().println(objectMapper.writeValueAsString(Result.ok()));
        } else {
            response.getWriter().println(objectMapper.writeValueAsString(Result.error("付款失败，可能存在购买商品数量大于库存")));
        }
    }

    /**
     * 确认收货
     *
     * @param request
     * @param response
     * @throws IOException
     */
    private void confirmReceive(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String idStr = request.getParameter("id");
        int id;
        try {
            id = Integer.parseInt(idStr);
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().println(objectMapper.writeValueAsString(Result.error("参数传入错误")));
            return;
        }
        boolean result = ordersService.confirmReceive(id);
        if (result) {
            response.getWriter().println(objectMapper.writeValueAsString(Result.ok()));
        } else {
            response.getWriter().println(objectMapper.writeValueAsString(Result.error("确认收货发生错误")));
        }
    }
}
